package cn.kgc.smbms.controller;

import cn.kgc.smbms.projo.User;
import cn.kgc.smbms.projo.UserExt;
import cn.kgc.smbms.service.RoleService;
import cn.kgc.smbms.service.UserService;
import cn.kgc.smbms.utils.Page;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/userManage")
public class UserSelectController {
    private Logger logger = Logger.getLogger(UserSelectController.class);
    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;

    @RequestMapping("/userLikeSelect")
    public String getUserList(Model model,
                              @RequestParam(value = "queryUserName", required = false) String queryUserName,
                              @RequestParam(value = "queryUserRole", required = false) String queryUserRole,
                              @RequestParam(value = "pageIndex", required = false) String pageIndex) {
        logger.debug("查询条件用户名为：" + queryUserName);
        logger.debug("查询条件用户角色为：" + queryUserRole);
        logger.debug("查询条件页码为：" + pageIndex);
        //int _queryUserRole = 0;
        List<UserExt> userList = null;
        //设置页码容量
        int pageSize = 4;
        //设置当前页码
        int currentPageNo = 1;
        if (queryUserName == null) {
            queryUserName = "";
        }
//        if (queryUserRole!=null&&!queryUserRole.equals("")){
//            _queryUserRole=Integer.parseInt(queryUserRole);
//        }
        if (pageIndex != null) {
            currentPageNo = Integer.valueOf(pageIndex);
        }
        //求出总数量
        int totalRecode = userService.userCount(queryUserName, queryUserRole);
//        Page<UserExt> page=new Page<>();
//        page.setPageNo(currentPageNo);
//        page.setPageSize(pageSize);
//        page.setTotalRecode(totalRecode);
//        int totalPageCount=page.getTotalPage();
//        //控制首页和尾页
//        if (currentPageNo<1){
//            currentPageNo=1;
//        }else if (currentPageNo>totalPageCount){
//            currentPageNo=totalPageCount;
//        }
        //求出总内容
        //
        userList = userService.selectUserLikeMoreValue(queryUserName, queryUserRole);
        //传值到view层
        model.addAttribute("list", userList);
        //model.addAttribute("totalPageCount",totalPageCount);
        // model.addAttribute("currentPageNo",currentPageNo);
        // model.addAttribute("totalRecode",totalRecode);


        return "userlist";
    }

    @RequestMapping("/userSelect")
    public String selectAllUserList(Model model, @RequestParam(value = "pageIndex", required = false) String pageIndex) {
        List<UserExt> list = null;
        int pageSize = 3;
        int currentPageNo = 1;
        if (pageIndex != null) {
            currentPageNo = Integer.valueOf(pageIndex);
        }
        //求出总数量
        int totalRecode = userService.selectUserCount();
        //求出总记录数
        int _currentPageNo = (currentPageNo - 1) * pageSize;
        list = userService.selectUserList(_currentPageNo, pageSize);
        Page<UserExt> page = new Page<>();
        page.setPageNo(currentPageNo);
        page.setPageSize(pageSize);
        page.setTotalRecode(totalRecode);
        int totalPageCount = page.getTotalPage();
        //控制首页和尾页
        if (currentPageNo < 1) {
            currentPageNo = 1;
        } else if (currentPageNo > totalPageCount) {
            currentPageNo = totalPageCount;
        }
        model.addAttribute("list", list);
        model.addAttribute("totalPageCount", totalPageCount);
        model.addAttribute("currentPageNo", currentPageNo);
        model.addAttribute("totalRecode", totalRecode);

        return "userlist";
    }

    @RequestMapping(value = "/useradd", method = RequestMethod.GET)
    public String addUser(@ModelAttribute("user") User user) {
        return "useradd";
    }

    @RequestMapping(value = "/useraddSave", method = RequestMethod.POST)
    public String addUserSave(@Valid User user, BindingResult bindingResult, HttpSession session,
                              @RequestParam(value = "idPicPath", required = false) MultipartFile upFile,
                              HttpServletRequest request) {
        if (bindingResult.hasErrors()) {
            logger.debug("add user validated has error===");
            return "useradd";
        }
//        String idPicPath = null;
//        //定义上传路径
//        String path = request.getServletContext().getRealPath("/WEB-INF/upload/");
//        if (!upFile.isEmpty()) {
//            //System.out.println(path+ File.separator);
//            //获取原文件名
//            String oldFileName = upFile.getOriginalFilename();
//            //获取文件名后缀
//            String suffex = FilenameUtils.getExtension(oldFileName);
//            int fileSize = 500000;
//            //判断文件大小
//            if (upFile.getSize() > fileSize) {
//                request.setAttribute("fileError", "文件大小不得超过50000");
//                return "useradd";
//            } else if (suffex.equalsIgnoreCase("jpg")
//                    || suffex.equalsIgnoreCase("jpeg")
//                    || suffex.equalsIgnoreCase("png")
//                    || suffex.equalsIgnoreCase("pneg")) {
//                //更改文件名称，确保不重复，采用当前系统时间＋随机数+_Personal.jpg
//                String fileName = System.currentTimeMillis() + RandomUtils.nextInt(0, 1000000) + "_Personal.jpg";
//                File targetFile = new File(path, fileName);
//                if (!targetFile.exists()) {
//                    targetFile.mkdirs();
//                }
//                try {
//                    upFile.transferTo(targetFile);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    request.setAttribute("fileError", "上传失败");
//                    return "useradd";
//                }
//                idPicPath=path+File.separator+fileName;
//
//
//            } else {
//                request.setAttribute("fileError", "上传图片格式不正确");
//                return "useradd";
//            }
//
//
//        }
        //user.setCreatedBy(session.getAttribute("user"));
        user.setCreationDate(new Date());
        //user.setIdPicPath(idPicPath);
        if (userService.insertNewUser(user)) {
            return "redirect:/userManage/userSelect";
        }
        return "redirect:/userManage/useradd";
    }

    //根据id查询
    @RequestMapping(value = "/view/{id}", method = RequestMethod.GET)
    public String selectUserById(@PathVariable String id, Model model) {
        logger.debug("view id============" + id);
        //调用service层的方法
//        User user=userService.getUserById(id);
//        model.addAttribute(user);
        return "userview";
    }
    //文件上传


}
